package com.book.servlet.auth;

import com.book.service.UserService;
import com.book.service.impl.UserServiceImpl;
import com.book.util.ThymeleafUtil;
import lombok.extern.java.Log;
import org.thymeleaf.context.Context;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/*
 **@Author:youpeng
 **Created on 2022/4/24
 */
@Log
@WebServlet("/login")
public class LoginServlet extends HttpServlet {

    UserService userService=new UserServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Cookie[] cookies = req.getCookies();
        if(cookies!=null){
            String username=null;
            String password=null;
            for (Cookie cookie:cookies){
                if(cookie.getName().equals("username")) username=cookie.getValue();
                if(cookie.getName().equals("password")) password=cookie.getValue();
            }
            if(username!=null&&password!=null){
                if (userService.auth(username,password, req.getSession())){
                    resp.sendRedirect("index");
                    return;
                }
            }
        }



        resp.setCharacterEncoding("UTF-8");
        Context context = new Context();
        if(req.getSession().getAttribute("login-failure")!=null){
            context.setVariable("failure",true);
            req.getSession().removeAttribute("login-failure");
        }
        if(req.getSession().getAttribute("user")!=null){
            resp.sendRedirect("index");
            return;
        }
        context.setVariable("msg",2);
        context.setVariable("as",123);
        context.setVariable("az",456);
        ThymeleafUtil.process("login.html",context,resp.getWriter());
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String remember = req.getParameter("remember");
        if(userService.auth(username,password, req.getSession())){
            if(remember!=null){
                Cookie cookie_username = new Cookie("username",username);
                cookie_username.setMaxAge(30*30*30);
                Cookie cookie_password = new Cookie("password",password);
                cookie_password.setMaxAge(30*30*30);
                resp.addCookie(cookie_username);
                resp.addCookie(cookie_password);
                resp.sendRedirect("index");
            }
        }else {
            req.getSession().setAttribute("login-failure",new Object());
            this.doGet(req,resp);
        }
    }
}
